package com.lv.suyiyong.hfrbusines.ui

import android.content.Intent
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.im.push.OfflineMessageDispatcher
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.LogUtil
import com.lv.common.utils.showToast
import com.lv.service.bean.FindProsBean
import com.lv.service.event.HomeTabChangeEvent
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfrbusines.R
import com.lv.suyiyong.hfrbusines.YgxApplication
import com.lv.suyiyong.hfrbusines.databinding.ActivityHomeBinding
import com.lv.suyiyong.hfrbusines.moudel.MainPageViewModel
import com.lv.suyiyong.hfrbusines.moudel.MainViewModel
import com.lv.suyiyong.hfrbusines.widget.HomeBottomTabWidget
import com.tencent.imsdk.v2.V2TIMConversationListener
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.util.SPUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel


@Route(path = ARoutUtils.HomeActivityURL)
class HomeActivity : BaseActivity<ActivityHomeBinding>() {
    @Autowired(name = "userInfo")
    @JvmField
    var mUserInfo: UserInfo? = null

    @Autowired(name = "tabId")
    @JvmField
    var mTabId: Int = 0
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val pageViewModel by viewModels<MainPageViewModel>()

    private val viewModel: MainViewModel by viewModel()
    private val serviceViewModel: ServiceViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_home
    override fun initView() {
        super.initView()
//        initStatusBar(this, true, true)
        YgxApplication.getInstance().init(GenerateTestUserSig.SDKAPPID)
        YgxApplication.getInstance().registerPushManually()
        ARouter.getInstance().inject(this)
//        mBinding.homeBottomTab.init(supportFragmentManager, pageViewModel)
        /*val permissions = mutableListOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
        )
        PermissionXUtils.checkPermissBefore(
            this, permissions,"用于在您浏览、搜索或参与特定活动时，向您展示当前城市服务信息，以提升体验。不授权该权限不影响APP的正常使用。",
            object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        Toast.makeText(this@HomeActivity, "所有申请的权限都已通过", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@HomeActivity, "您拒绝了如下权限：$deniedList", Toast.LENGTH_SHORT).show()
                    }
                }
            },
        )*/

    }


//    private fun loadUI() {
//        val intent: Intent
//        if (AppConfig.DEMO_UI_STYLE === 0) {
//            intent = Intent(this@SplashActivity, MainActivity::class.java)
//        } else {
//            intent = Intent(this@SplashActivity, MainMinimalistActivity::class.java)
//        }
//        val dataIntent = getIntent()
//        intent.putExtras(dataIntent!!)
//        if (dataIntent != null) {
//            val ext = dataIntent.getStringExtra(TUIConstants.TUIOfflinePush.NOTIFICATION_EXT_KEY)
//            intent.putExtra(TUIConstants.TUIOfflinePush.NOTIFICATION_EXT_KEY, ext)
//        }
//        startActivity(intent)
//        initUnreadCount()

//    }

    override fun initData() {
        super.initData()
//        mBinding.homeBottomTab.setTabGone(3)
        doWorkManager()
        UserDbHelper.getLiveUserInfo(this).observeKt { userInfo ->
            if (userInfo != null && !userInfo.id.isNullOrEmpty()) {
//                YgxApplication.getInstance().registerPushManually()
                sendIMToken(userInfo.phone)
            }
        }
    }

    private fun sendIMToken(phone: String?) {
        val userphone = phone ?: ""
        val token = SPUtils.getInstance().getString("im_register", "")
        val appVersionCode = AppUtils.getAppVersionName()
        val brand = DeviceUtils.getManufacturer()
        LogUtils.e("aaa")
        lifecycleScope.launchWhenCreated {
            this.launch {
                val imMap = mutableMapOf<String, String>(
                    "phone" to userphone,
                    "plat" to brand,
                    "sion" to appVersionCode,
                    "code" to "2",
                    "ptoken" to token,
                )
                val result: DataResult<BaseYgxRsp> =
                    myScope.async { viewModel.saveTX(imMap) }.await()
            }
        }
    }

    /**
     * 执行后台任务
     */
    private fun doWorkManager() {
        YgxToolsKt.doWorkManager(this)
    }

    override fun initConfig() {
        super.initConfig()
//        checkUserInfo()
        pageViewModel.setPage(mTabId)
        mBinding.homeBottomTab.init(supportFragmentManager, pageViewModel)
//        V2TIMManager.getConversationManager()
//            .addConversationListener(v2TIMConversationListener)
        LogUtil.e("HomeActivity======Opencount====", "openCount")
//        YgxApplication.getInstance().registerPushManually()
        initUnreadCount()
//        handleOfflinePush()
        findPros()
//        findPros2()
        findPros1()
    }

    private fun findPros() {
        startLoading()
        val map = mutableMapOf<String, String>(
            "telAddress" to "1",
            "spuCategory" to "1",
            "telCategory" to "1",
            "professional" to "1",//查所有业务员
            "issuer" to "1",//查所有发行人员
        )
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findPros(map) }.await()
            parseFindProsResult(result)
        }
    }

    private fun findPros1() {
        startLoading()
        val map = mutableMapOf<String, String>(
            "address" to "1",
            "category" to "1",
//            "receiptAddress" to "1",
            "cardColor" to "1",
            "nearByProvince" to "1",
            "nearByCity" to "1",
        )
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findPros(map) }.await()
            parseFindProsResult(result)
        }
    }


    private fun parseFindProsResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<FindProsBean> { code, data, message, result ->
                data?.let {

                    lifecycleScope.launch {
                        //地址信息
                        this.launch {
                            val addressList = it.address
                            if (addressList != null) {
                                YgxToolsKt.saveAddressRoom(this@HomeActivity, addressList)
                            }
                        }
//                        this.launch {
//                            val addressList = it.receiptAddress
//                            if (addressList != null) {
//                                saveAddressAllRoom(this@HomeActivity, addressList)
//                            }
//                        }
//                        //四级地址选择器数据
//                        this.launch {
//                            val addressList = it.newreceiptAddress
//                            if (addressList != null && addressList.isNotEmpty()) {
//                                YgxToolsKt.saveNewReceiptAddressAllRoom(
//                                    this@HomeActivity,
//                                    addressList
//                                )
//                            }
//                        }
                        this.launch {
                            //分类信息
                            val categoryList = it.category
                            if (categoryList != null) {
                                YgxToolsKt.saveRoomCategory(this@HomeActivity, categoryList)
                            }
                        }

                        //找货大全信息
                        this.launch {
                            val categoryList = it.telCategory
                            if (categoryList != null) {
                                YgxToolsKt.saveCardCategory(this@HomeActivity, categoryList)
                            }
                        }
                        //新分类信息
                        this.launch {
                            val nearByProvince = it.nearByProvince
                            val nearByCity = it.nearByCity
                            if (nearByProvince != null ) {
                                YgxToolsKt.saveNewTelCategoryRoom(
                                    this@HomeActivity, nearByProvince
                                )
                            }
                            if (nearByCity != null ) {
                                YgxToolsKt.saveNewTelCategoryCityRoom(
                                    this@HomeActivity, nearByCity
                                )
                            }
                        }
                        //商品分类信息
                        this.launch {
                            val categoryList = it.spuCategory
                            if (categoryList != null) {
                                YgxToolsKt.saveGoodsCategory(this@HomeActivity, categoryList)

                            }
                        }
                        this.launch {
                            val addressList = it.telAddress
                            if (addressList != null) {
                                YgxToolsKt.saveCardAddress(this@HomeActivity, addressList)
                            }
                        }
                        this.launch {
                            //字体信息
                            val cardColorList = it.cardColor
                            if (cardColorList != null) {
                                YgxToolsKt.saveCardColorInfo(this@HomeActivity, cardColorList)
                            }
                        }
                        this.launch {
                            //业务员信息 DEF
                            val professionalBeans = it.professional
                            if (professionalBeans != null) {
                                YgxToolsKt.saveSalerInfos(this@HomeActivity, professionalBeans)
                            }
                        }
                        this.launch {
                            //发行人员信息   BC
                            val suerBeans = it.issuer
                            if (suerBeans != null) {
                                YgxToolsKt.saveSuerInfos(this@HomeActivity, suerBeans)
                            }
                        }

                    }
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
        data.onFailure {
            LogUtils.e("eee")
        }
    }


    private fun initUnreadCount() {
        V2TIMManager.getConversationManager()
            .getTotalUnreadMessageCount(object : V2TIMValueCallback<Long?> {
                override fun onSuccess(aLong: Long?) {
                    val unreadCount = aLong ?: 0
                    setUnReadMessageCount(unreadCount)

                }


                override fun onError(code: Int, desc: String) {
                    LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                }
            })
        V2TIMManager.getConversationManager()
            .addConversationListener(object : V2TIMConversationListener() {
                // 收到所有会话的未读总数变更通知
                override fun onTotalUnreadMessageCountChanged(totalUnreadCount: Long) {
                    super.onTotalUnreadMessageCountChanged(totalUnreadCount)
                    setUnReadMessageCount(totalUnreadCount)
                }
            })


    }

    private fun setUnReadMessageCount(unreadCount: Long) {
        var unreadStr = "" + unreadCount
        if (unreadCount > 100) {
            unreadStr = "99 +"
        }
        mBinding.homeBottomTab.setMessageCount(unreadStr)
        // update Huawei offline push Badge
        OfflineMessageDispatcher.updateBadge(this@HomeActivity, unreadCount.toFloat().toInt())
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
    }

    override fun onResume() {
        super.onResume()
        val page = pageViewModel.getPage() ?: 0
        initToolBar(page)
    }

    override fun initEvents() {
        super.initEvents()
        rigestEventBus()
        mBinding.homeBottomTab.setOnTabPagerListener(object : HomeBottomTabWidget.TabPagerListener {
            override fun OnClickTab(position: Int) {
                initToolBar(position)
            }
        })
    }

    private fun initToolBar(page: Int) {
        when (page) {
            0, 1, 3 -> {
                initStatusBar(this, true, false)
            }

            else -> {
                initStatusBar(this, true, true)
            }
        }
    }

    private fun rigestEventBus() {
        LiveEventBus.get(
            HomeTabChangeEvent::class.java,
        ).observe(
            this
        ) { s ->
            if (s != null) {
                val tab = s.tab
                mTabId = tab
                changeHomeTab()
            }
        }
    }

    private fun changeHomeTab() {
        pageViewModel.setPage(mTabId)
        mBinding.homeBottomTab.init(supportFragmentManager, pageViewModel)
    }

//    private val v2TIMConversationListener: V2TIMConversationListener =
//        object : V2TIMConversationListener() {
//            // 3.1 收话新增的回调
//            @RequiresApi(api = Build.VERSION_CODES.N)
//            override fun onNewConversation(conversationList: List<V2TIMConversation>) {
//                super.onNewConversation(conversationList)
//                LogUtil.e("onNewConversation", "onNewConversation")
//            }
//
//            // 3.2 收到会话更新的回调
//            @RequiresApi(api = Build.VERSION_CODES.N)
//            override fun onConversationChanged(conversationList: List<V2TIMConversation>) {
//                if (conversationList.isNotEmpty()) {
//                    val v2TIMConversation = conversationList[0]
////                    checkLoginOtherDevice(v2TIMConversation)
//                }
//            }
//
//        }

    /*private fun checkLoginOtherDevice(v2TIMConversation: V2TIMConversation) {
        val chatTag = SPStaticUtils.getString(Constants.KEY_CHAT_TOKEN, "aaa")
        val userID = v2TIMConversation.userID
        if (mUserInfo?.txaccid == userID) {
            val customText = v2TIMConversation.lastMessage.customElem
            val dataCustom = customText ?: return
            val customJson = dataCustom.data.toString(Charsets.UTF_8)
            val jsonType = object : TypeToken<CustomMessageBean?>() {}.type
            val jt: CustomMessageBean = GsonUtils.fromJson(customJson, jsonType)
            val idSyyAccid = jt.id_syy_accid
            val split = idSyyAccid.split("速易甬".toRegex()).toTypedArray()
            if (mUserInfo?.txaccid != split[1]) {
                return
            }
            if (!TextUtils.isEmpty(chatTag) && chatTag != "aaa" && split[0] != chatTag) {
                TUILogin.logout(object : TUICallback() {
                    override fun onSuccess() {
                        YgxUtilsKt.setAppToken("", "", "")
                        UserDbHelper.deleteUserInfo(this@HomeActivity)
                        V2TIMManager.getConversationManager()
                            .removeConversationListener(null)
                        ARouter.getInstance().build(ARoutUtils.LoginOutActivity).navigation()

//                        showLoginOutDialog()
                    }

                    override fun onError(errorCode: Int, errorMessage: String?) {
                    }
                })

            }
        }
    }*/

    /*private var mTipsDialog: HintDialog? = null
    private fun showLoginOutDialog() {
        val time = TimeUtil.getTime()
        mTipsDialog = HintDialog(
            this@HomeActivity,
            "提示",
            "您的帐号$time 在其他设备登录，是否重新登录",
            false,
            false,
            OnDialogSureListener {
                ARouter.getInstance().build(ARoutUtils.LoginActivityURL).navigation()
                finish()
            },
            false,
            false
        )
        if (!isFinishing) {
            mTipsDialog?.show()
        }
    }*/

    override fun onBackPressed() {
        super.onBackPressed()
//        exitProcess(0)
        moveTaskToBack(true)

    }

//    private var exitTime: Long = 0
//
//    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit()
//            return false
//        }
//        return super.onKeyDown(keyCode, event)
//    }
//
//    private fun exit() {
//        if (System.currentTimeMillis() - exitTime > 2000) {
//            showToast("再按一次退出程序")
//            exitTime = System.currentTimeMillis()
//        } else {
//            exitProcess(0)
//        }
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (supportFragmentManager.fragments.size > 0) {
            val fragments = supportFragmentManager.fragments
            for (fragment in fragments) {
                fragment.onActivityResult(requestCode, resultCode, data)
            }
        }
//        if (resultCode == RESULT_OK) {
//            when (requestCode) {
//                0 -> {
//
//                }
//            }
//        }

    }

    override fun onDestroy() {
        super.onDestroy()
//        if (mTipsDialog?.isShowing == true) {
//            mTipsDialog?.dismiss()
//        }
    }
}